<template>
  <main role="main">
    <div class="header-nav">
      <div class="clearfix">
        <div class="container">
          <div class="row">
            <div class="col-12">
              <a v-on:click="foldSwitchStatus = !foldSwitchStatus" style="cursor: pointer">
                <span v-show="foldSwitchStatus">▲</span>
                <span v-show="!foldSwitchStatus">▼</span>
              </a>
              <a v-on:click="onClickLevel1(0)" id="category-0" href="javascript:;" class="cur">全部</a>
              <a v-for="o in level1" :key="o" v-on:click="onClickLevel1(o.problemCategoryId)" v-bind:id="'category-' + o.problemCategoryId" href="javascript:;">{{o.problemCategoryName}}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="skill clearfix" v-show="foldSwitchStatus">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <a v-on:click="onClickLevel2(11111111)" id="category-11111111" href="javascript:;" class="on">不限</a>
            <a v-for="o in level2" :key="o" v-on:click="onClickLevel2(o.problemCategoryId)" v-bind:id="'category-' + o.problemCategoryId" href="javascript:;">{{o.problemCategoryName}}</a>
            <div style="clear:both"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="album py-4 bg-light">

      <div class="container">

        <div>

          <div class="card mb-4 shadow-sm">
            <br>

            <el-row>
              <el-col :span="1">

              </el-col>
              <el-col :span="6">
                <label>试题难度</label>
              </el-col>
              <el-col :span="1" v-if="loginMember.userGroupId === USER_GROUP.Administrators.key">

              </el-col>
              <el-col :span="6" v-if="loginMember.userGroupId === USER_GROUP.Administrators.key">
                <label>公开试题</label>
              </el-col>
              <el-col :span="1">

              </el-col>
              <el-col :span="7">
                <label>试题名称</label>
              </el-col>
              <el-col :span="2">

              </el-col>
            </el-row>

            <el-row>

              <el-col :span="1">

              </el-col>


              <el-col :span="6">
                <el-select v-model="problemTagSlug" placeholder="试题难度">
                  <el-option
                      v-for="item in PROBLEM_TAG_SLUGS"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-col>

              <el-col :span="1" v-if="loginMember.userGroupId === USER_GROUP.Administrators.key">

              </el-col>

              <el-col :span="6" v-if="loginMember.userGroupId === USER_GROUP.Administrators.key">

                <el-select v-model="isPublic" placeholder="Select">
                  <el-option
                      v-for="item in YES_NO"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>

              </el-col>

              <el-col :span="1"></el-col>


              <el-col :span="7">
                <el-input v-model="keyword" placeholder="Please input keyword" />

              </el-col>

              <el-col :span="2">
                <el-button type="primary" v-on:click="list(1)">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </el-col>

              <el-col v-if="identify" :span="2">
                <el-button  type="primary" v-on:click="creatProblem()">
                  创建
                </el-button>
              </el-col>
            </el-row>

            <br>

            <el-table
                :data="problems"
                stripe
                style="width: 100%"

            >
              <el-table-column width="60" prop="userSubmitResult">
                <template #default="scope">
<!--                  <span v-bind:class="{'success' : scope.row.userSubmitResult ==='1',-->
<!--                                        'danger' : (scope.row.userSubmitResult === SUBMISSION_RESULT.CE.key || scope.row.userSubmitResult === SUBMISSION_RESULT.WA.key),-->
<!--                                        'warning' : (scope.row.userSubmitResult !== SUBMISSION_RESULT.CE.key && scope.row.userSubmitResult !== SUBMISSION_RESULT.AC.key-->
<!--                                        && scope.row.userSubmitResult !== SUBMISSION_RESULT.WA.key)}">-->
<!--                        {{scope.row.userSubmitResult}}-->
<!--                  </span>-->
                  <span v-show="scope.row.userSubmitResult ==='1'" class="success">
                       AC
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="problemId" label="ID" width="80"> </el-table-column>
              <el-table-column prop="problemName" label="试题名称" width="280"> </el-table-column>
              <el-table-column prop="problemCategories" label="分类" width="200"> </el-table-column>
              <el-table-column  label="标签" width="80">
                <template #default="scope" >
                  <span v-bind:class="{'error' :  scope.row.problemTags === PROBLEM_TAG_SLUGS[1].value,
                                        'danger' : scope.row.problemTags === PROBLEM_TAG_SLUGS[2].value,
                                        'warning' : scope.row.problemTags === PROBLEM_TAG_SLUGS[3].value,
                                        'success' : scope.row.problemTags === PROBLEM_TAG_SLUGS[4].value,
                                     }">
                    {{scope.row.problemTags}}
                  </span>
                </template>

              </el-table-column>
              <el-table-column prop="totalSubmission" label="全部提交" width="80"> </el-table-column>
              <el-table-column prop="acceptedSubmission" label="通过提交" width="80"> </el-table-column>
              <el-table-column v-if="identify" label="操作" width="260">
                <template #default="scope" >
                  <el-button size="small" type="success" @click="handleDoProblem(scope.$index, scope.row)"
                  >刷题</el-button
                  >
                  <el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button>
<!--                  <el-button-->
<!--                      size="small"-->
<!--                      color="#626aef"-->
<!--                      @click="exportProblem(scope.$index, scope.row)"-->

<!--                  >导出</el-button>-->
                </template>
              </el-table-column>

            </el-table>
            <br>
            <div id="problem-list-pagination">

              <pagination ref="pagination" v-bind:list="list" v-bind:itemCount="8"></pagination>
            </div>

          </div>
          <!--          <h3 v-show="courses.length === 0">暂无此类试题</h3>-->
        </div>

        <br>

      </div>
    </div>


  </main>
</template>

<script>
import Pagination from "./Pagination.vue";
import {Search} from '@element-plus/icons-vue/dist/index.min'
import API from '../api/questionManager'
export default {
  components: {Pagination, Search},
  name: 'the-problem-list',
  props: {

  },

  data: function () {
    return {
      foldSwitchStatus: false,
      optionWidth: 180,
      totalCount:0,
      identify:true,
      level1: [],
      level2: [],
      categorys: [],
      level1Id: 0,
      level2Id: 0,
      problems: [],
      problemCategoryId: 0,
      keyword: "",
      problemTagSlug: 0,
      isPublic: "Yes",
      PROBLEM_TAG_SLUGS: PROBLEM_TAG_SLUGS,
      YES_NO: YES_NO,
      loginMember: {},
      USER_GROUP: USER_GROUP,
      SUBMISSION_RESULT: SUBMISSION_RESULT,
      SERVER_DOMAIN: SERVER_DOMAIN,
      CURRENT_PROBLEM_LIST_PAGE: CURRENT_PROBLEM_LIST_PAGE,
    }
  },

  mounted() {
    let _this = this;
    console.log(584)
    if(this.$store.getters['user/identify']===2){
      this.identify = false
      console.log(this.identify)
    }

    _this.$refs.pagination.size = 50;
    _this.loginMember = Tool.getLoginMember();
    if(_this.loginMember.userGroupId === USER_GROUP.Administrators.key) {
      _this.optionWidth = 240;
    }
    _this.allCategory()
    let currentPage = LocalStorage.get(CURRENT_PROBLEM_LIST_PAGE) || 1;
    _this.list(currentPage);
  },

  methods: {

    handleDoProblem(pid, row) {
      let detail ={}
      detail.id = row.problemId
      let token = localStorage.getItem('token')
      API.questionDetail(detail,token).then(res=>{
        LocalStorage.set(CURRENT_PROBLEM,res.data.content)
      }).then(res=>{
        this.$router.push({
          path:'/question',
          query: {
            questionCount:this.totalCount
          }
        })
      }).catch(e=>{
        console.log(e)
      })

    },


    handleEdit(index, row) {
      let param = Object.assign({}, row)
      let detail ={}
      detail.id = row.problemId
      let token = localStorage.getItem('token')
      API.questionDetail(detail,token).then(res=>{
        param.testcase = res.data.content.testcase
        LocalStorage.set(CURRENT_EDIT_PROBLEM, param);
        this.$router.push({
          path: "/public/questionManager",
        });
      }).catch(e=>{
        console.log(e)
      })
      console.log(param)
      // LocalStorage.set(CURRENT_EDIT_PROBLEM, param);
      // this.$router.push({
      //   path: "/public/questionManager",
      // });

    },

    handleDelete(index, row) {
      console.log(row.problemId)
      let _this = this;

      Confirm.show("Are You Sure To Delete Problem " + row.problemId + " ?", function () {
        let param = {}
        let token = localStorage.getItem('token')
        param.id = row.problemId
       API.questionDelete(param,token).then((res) => {
          Loading.hide();
          if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
            _this.$router.push({path: '/home'});
            return;
          }
          if (res.data.success) {
            _this.$notify.success("Delete Problem " + row.problemId + " Success...");
            this.$router.go(0);
          }
        }).catch((err) => {
          Loading.hide();
          console.log(err);
        });
      });


    },



    assembleExportText(row, submissions, testCases) {
      let problemName     = row.problemName ;
      let timeLimit       = row.timeLimit   ;
      let memoryLimit     = row.memoryLimit ;
      let description     = row.description ;
      let hint            = row.hint        ;
      let inputFormat     = row.inputFormat ;
      let outputFormat    = row.outputFormat;
      let inputSample     = row.sampleInput ;
      let outputSample    = row.sampleOutput;

      let tagNames = [
        "【标题】",
        problemName,
        "【题目描述】",
        description,
        "【输入格式】",
        inputFormat,
        "【输出格式】",
        outputFormat,
        "【输入样例】",
        inputSample,
        "【输出样例】",
        outputSample,
        "【时间限制】",
        timeLimit,
        "【内存限制】",
        memoryLimit,
        "【提示】",
        hint,
        "【测试集】\n"
      ]
      let exportText = tagNames.join("\n");
      let inputTag = "【输入】\n";
      let outputTag = "【输出】\n";

      for (let i = 0; i < testCases.length; i++) {
        let checkpointTag = "【测试点 "+ (i+1) +"】\n";

        exportText += checkpointTag;
        exportText += inputTag;
        exportText += testCases[i].input;
        exportText += "\n"
        exportText += outputTag;
        exportText += testCases[i].output;
        exportText += "\n"
      }

      let standardAnswer = "";
      for (let i = 0; i < submissions.length; i++) {
        let submission = submissions[i]
        if (submission.judgeScore === 100) {
          standardAnswer = submission.language.languageName + "\n" + submission.code;
          break;
        }
      }
      exportText += "【知识点分类】\n";
      exportText += row.problemCategories;
      exportText += "\n"
      exportText += "【标准例程】\n";
      exportText += standardAnswer;
      exportText += "\n"
      exportText += "说明：“【】”内的提示请不要改动，只需要修改后面的灰色文字。测试集必须是10个。题目描述请尽量清晰易懂，请多加几个示例以便学生进行本机验证."
      return exportText;
    },

    setQueryCondition(problemCategoryId, keyword) {
      this.problemCategoryId = problemCategoryId;
      this.keyword = keyword;
    },


    /**
     * 题目查询
     */
    list(page) {
      let _this = this;
      Loading.show();
      LocalStorage.set(CURRENT_PROBLEM_LIST_PAGE, page);
      let params={}
      let token = localStorage.getItem('token')
      // params.size = 50
      // params.current = 1
      params.current = page
      params.size =_this.$refs.pagination.size
      params.keyword = _this.keyword,
      params.categoryId = _this.problemCategoryId
      if(_this.problemTagSlug!==0) {
        params.tagId = _this.problemTagSlug
      }
      params.isPublic = _this.isPublic
      let loginMember = Tool.getLoginMember();
      API.questionList(params,token).then((res) => {
        Loading.hide();
        console.log(res.data)
        if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }
        if (res.data) {
          _this.problems = res.data.content.records;
          this.totalCount = res.data.content.total
          _this.$refs.pagination.render(page, res.data.content.total);
        }
      }).catch((err) => {
        Loading.hide();
        console.log(err);
      });
      // _this.$axios.post('/training/getProblemByCondition', {
      //   page: page - 1,
      //   size: _this.$refs.pagination.size,
      //   keyword: _this.keyword,
      //   problemCategoryId: _this.problemCategoryId,
      //   problemTagSlug: _this.problemTagSlug,
      //   isPublic: _this.isPublic,
      //   userName: loginMember.userName,
      // }).then((res) => {
      //   Loading.hide();
      //   if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
      //     _this.$router.push({path: '/home'});
      //     return;
      //   }
      //   if (res.data) {
      //     _this.problems = res.data.list;
      //     _this.$refs.pagination.render(page, res.data.total);
      //   }
      // }).catch((err) => {
      //   Loading.hide();
      //   console.log(err);
      // });

    },

    /**
     * 所有分类查询
     */
    allCategory() {
      let _this = this;
      let token = localStorage.getItem('token')
      API.questionCategoryList(token).then((res) => {
        if(res.data.success) {
          _this.categorys = res.data.content;
          // 将所有记录格式化成树形结构
          _this.level1 = [];
          for (let i = 0; i < _this.categorys.length; i++) {
            let c = _this.categorys[i];
            if (c.problemCategoryParentId === 0) {
              _this.level1.push(c);
            } else {
              _this.level2.push(c);
            }
          }
          console.log(66)
          console.log(res.data.content)
          console.log(this.level1)
          console.log(this.level2)
        }
      }).catch((err) => {
        console.log(err);
      });


    },

    /**
     * 点击一级分类时
     * @param level1Id
     */
    onClickLevel1(level1Id) {
      let _this = this;

      // 点击一级分类时，设置变量，用于课程筛选
      // 二级分类id为空，
      // 如果点击的是【全部】，则一级分类id为空
      _this.level2Id = null;
      _this.level1Id = level1Id;


      // 点击一级分类时，显示激活状态
      $("#category-" + level1Id).siblings("a").removeClass("cur");
      $("#category-" + level1Id).addClass("cur");

      // 点击一级分类时，二级分类【无限】按钮要设置激活状态
      $("#category-11111111").siblings("a").removeClass("on");
      $("#category-11111111").addClass("on");

      // 注意：要先把level2中所有的值清空，再往里放
      _this.level2 = [];
      let categorys = _this.categorys;
      // 如果点击的是【全部】，则显示所有的二级分类
      if (level1Id === 0) {
        for (let i = 0; i < categorys.length; i++) {
          let c = categorys[i];
          if (c.problemCategoryParentId !== 0) {
            _this.level2.push(c);
          }
        }
      }
      // 如果点击的是某个一级分类，则显示该一级分类下的二级分类
      if (level1Id !== 0) {
        for (let i = 0; i < categorys.length; i++) {
          let c = categorys[i];
          if (c.problemCategoryParentId === level1Id) {
            _this.level2.push(c);
          }
        }
      }
      _this.setQueryCondition(_this.level1Id, "");
      _this.list(1);
      // 重新加载课程列表
      //_this.listCourse(1);
    },

    /**
     * 点击二级分类时
     * @param level1Id
     */
    onClickLevel2(level2Id) {
      let _this = this;
      $("#category-" + level2Id).siblings("a").removeClass("on");
      $("#category-" + level2Id).addClass("on");

      // 点击二级分类时，设置变量，用于课程筛选
      // 如果点击的是【无限】，则二级分类id为空
      if (level2Id === 11111111) {
        _this.level2Id = _this.level1Id;
      } else {
        _this.level2Id = level2Id;
      }

      _this.setQueryCondition(_this.level2Id, "");
      _this.list(1);

      // 重新加载课程列表
      //_this.listCourse(1);
    },
    creatProblem(){
      localStorage.removeItem('CURRENT_EDIT_PROBLEM')
      this.$router.push({
        path:'/public/questionManager'
      })
    }
  },

}
</script>

<style scoped>
#problem-list-pagination {
  padding-left: 20px;
}

/* 头部 一级分类 */
.header-nav {
  height: auto;
  background: #fff;
  box-shadow: 0 8px 16px 0 rgba(28,31,33,.1);
  padding: 16px 0;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
  /*background-color: #d6e9c6;*/
}
.header-nav>div {
  width: 100%;
  padding-left: 12px;
  box-sizing: border-box;
  margin-left: auto;
  margin-right: auto;
  /*background-color: #B4D5AC;*/
}
.header-nav a {
  float: left;
  font-size: 16px;
  color: #07111b;
  line-height: 50px;
  height: 45px;
  position: relative;
  margin-right: 46px;
  font-weight: 700;
}
.header-nav a:hover {
  color: #c80;
}
.header-nav a.cur {
  color: #c80;
}
.header-nav a.cur:before {
  display: block;
}
.header-nav a:before {
  display: none;
  content: ' ';
  position: absolute;
  bottom: 0;
  background: #c80;
  width: 16px;
  height: 3px;
  left: 50%;
  margin-left: -8px;
}
/* 二级分类 */
.skill {
  width: 100%;
  padding: 24px 0 0;
  position: relative;
  margin: 0 auto;
}
.skill a.on {
  color: #c80;
  background: rgba(204,136,0,.1);
}
.skill a {
  float: left;
  margin-right: 20px;
  padding: 0 12px;
  font-size: 14px;
  color: #4d555d;
  line-height: 32px;
  border-radius: 6px;
  margin-bottom: 12px;
}
.skill a:hover {
  background: #d9dde1;
}

label {
  font-weight: bold;
}

.success {
  color: #67c23a;
}

.warning {
  color: #ffc107;
}

.danger {
  color: #db6f6e;
}

.error {
  color: #ff0400;
}
</style>
